/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package image.histogram;

import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import org.jfree.chart.*;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.statistics.*;
//import sun.awt.image.WritableRasterNative;

/**
 *
 * @author tommy
 */
public class Histogram {

	private BufferedImage image;
	private HistogramDataset statistics;
	private double samples[];
	private final int binsQty = 256; // Numero de intervalos del histograma

	public Histogram(BufferedImage image) {
		Raster r = image.getData();

		this.image = image;
		this.statistics = new HistogramDataset();
		this.statistics.setType(HistogramType.FREQUENCY);
		this.samples = new double[image.getWidth()*image.getHeight()];
		this.samples = r.getSamples(0, 0, image.getWidth() - 1, image.getHeight() - 1,0,this.samples);
		this.statistics.addSeries("Histogram", this.samples, binsQty, 0, 255);
	}

	public BufferedImage getHistogram() {
		boolean show = false;
		boolean toolTips = false;
		boolean urls = false;
		String plotTitle = "Image GrayScale Histogram";
		String xaxis = "Pixel Values";
		String yaxis = "Freq";
		PlotOrientation orientation = PlotOrientation.VERTICAL;
		
		
		if (image.getType() != BufferedImage.TYPE_BYTE_GRAY) {
			return null;
		}
		JFreeChart chart = ChartFactory.createHistogram(plotTitle, xaxis, yaxis,
			this.statistics, orientation, show, toolTips, urls);
		
		int width = 500;
		int height = 300;
		return chart.createBufferedImage(width, height);
	}
	
	public double[] getEqualizedLevels() {
		BufferedImage ret;
		
		// cumulative distribution function
		double[] cdf = new double[binsQty];
		double[] equalization = new double[binsQty];
		int qty, acum, min;
		
		acum = 0;
		min = Integer.MAX_VALUE;
		
		// generates cumulative dist. function and its min value cdf_min
		for (int i = 0 ; i < binsQty ; i++) {
			qty = (int)this.statistics.getYValue(0, i);
			
			if (qty < min) {
				min = qty;
			}
			acum += qty;
			cdf[i] = acum;
		}
		
		// equalization process
		for (int i = 0 ; i < binsQty ; i++) {
			equalization[i] = Math.round(((cdf[i] - min) / (image.getHeight() * image.getWidth() - min)) * (binsQty - 1));
		}
		
		return equalization;
	}
}
